
/**
 * 校验图片宽高
 * @param {file} file
 * @param {number} w
 * @param {number} h
 */
export const checkImgWH = (file, w, h) => {
  return new Promise((resolve) => {
    const isImg = checkImgType(file)
    if (!isImg) return resolve(['仅支持图片文件', null])

    const reader = new FileReader()

    reader.onload = event => {
      const data = event.target.result

      // 加载图片获取图片真实宽度和高度
      const image = new Image()
      image.onload = () => {
        const { width, height } = image

        const flag = width === w && height === h
        resolve([flag ? null : `图片尺寸应为 ${w}*${h}`, { width, height }])
      }

      image.src = data
    }

    reader.readAsDataURL(file)
  })
}

/**
 * 校验文件大小
 * @param {file} file
 * @param {number} maxSize - 单位为 kb
 */
export const checkMaxSize = (file, maxSize) => {
  const size = file.size / 1024

  return size <= maxSize
}

/**
 * 校验图片类型
 * @param file
 * @param {array|string} tyeps - [jpg, png] 或 jpg
 */
export const checkImgType = (file, types) => {
  const fileType = file.type

  if (typeof types === 'string') types = [types]

  const reg = new RegExp(types ? `^image/(${types.join('|')})$` : '^image/')

  return reg.test(fileType)
}

/**
 * 校验视频类型
 */
export const checkVideoType = (file, types) => {
  const fileType = file.type

  if (typeof types === 'string') types = [types]

  const reg = new RegExp(types ? `^video/(${types.join('|')})$` : '^video/')

  return reg.test(fileType)
}

// 获取视频对象
export const queryVideo = file => {
  return new Promise((resolve) => {
    const isVideo = checkVideoType(file)
    if (!isVideo) return resolve(['仅支持视频文件', null])

    const videoUrl = URL.createObjectURL(file)
    const videoDom = document.createElement('video')

    videoDom.onloadedmetadata = () => {
      URL.revokeObjectURL(videoUrl)

      resolve([null, videoDom])
    }

    videoDom.src = videoUrl
    videoDom.load()
  })
}

/**
 * 校验视频宽高
 */
export const checkVideoWH = async (file, w, h) => {
  const res = await queryVideo(file)
  if (res[0]) return res

  const { videoWidth: width, videoHeight: height } = res[1]

  return [width === w && height === h ? null : `视频尺寸应为${w}*${h}`, { width, height }]
}
